/**
 * 公共方法 分页计算
 * @param req
 * @returns {{query: {}, pageSize: (number|number), currentPage: (number|number)}}
 */
const path = require("path");
const fs = require("fs");
const adminAuth = require("../middlewares/admin-auth");
const colors = require("colors");

/**
 * 分页计算
 * @param req
 * @returns {{offset: number, query: {}, pageSize: (number|number), currentPage: (number|number)}}
 */
exports.paging = function (req) {
  const query = req.query || {};
  // 当前是第几页，如果不传，那就是第一页
  const currentPage = Math.abs(Number(query.currentPage)) || 1;
  // 每页显示多少条数据，如果不传，那就显示10条
  const pageSize = Math.abs(Number(query.pageSize)) || 10;
  // 计算 offset
  const offset = (currentPage - 1) * pageSize;
  return { query, currentPage, pageSize, offset };
};

/**
 * 加载路由
 * @param app express实例
 * @param directoryPath 路径
 * @param apiPrefix API 前缀
 */
exports.loadRoutesFromDirectory = (app, directoryPath, apiPrefix = "") => {
  const files = fs.readdirSync(directoryPath);
  files.forEach((file) => {
    const filePath = path.join(directoryPath, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      // 如果是目录，则递归调用，并将目录名添加到 API 前缀中
      this.loadRoutesFromDirectory(app, filePath, `${apiPrefix}/${file}`);
    } else if (file.endsWith(".js")) {
      // 如果是 .js 文件，则加载并挂载路由模块
      const moduleName = path.basename(file, ".js");
      const routeModule = require(filePath);
      // 使用目录名和模块名构建完整的路由前缀
      const fullApiPrefix = `${apiPrefix}/${moduleName}`;
      console.log(
        colors.blue(`路由：${fullApiPrefix}`) + colors.green("  挂载就绪~"),
      );
      switch (moduleName) {
        case "attachments":
          app.use(fullApiPrefix, routeModule);
          break;
        case "auth":
          app.use(fullApiPrefix, routeModule);
          break;
        default:
          app.use(fullApiPrefix, adminAuth, routeModule);
          break;
      }
    }
  });
};
/**
 * 欢迎信息
 */
exports.welcome = () => {
  console.log(
    colors.blue(
      "\n" +
        "                      _                                   \n" +
        "                     | |                                  \n" +
        "   __      __   ___  | |   ___    ___    _ __ ___     ___ \n" +
        "   \\ \\ /\\ / /  / _ \\ | |  / __|  / _ \\  | '_ ` _ \\   / _ \\\n" +
        "    \\ V  V /  |  __/ | | | (__  | (_) | | | | | | | |  __/\n" +
        "     \\_/\\_/    \\___| |_|  \\___|  \\___/  |_| |_| |_|  \\___|\n" +
        "                                                          \n" +
        "                                                          \n" +
        "    您好！欢迎使用 node-admin-api 开源项目         \n" +
        "    项目已启动 ~                             \n" +
        "                                                          \n" +
        "                                                          \n" +
        "                                                          \n",
    ),
  );
};
